<template>
  <div class="export-page">
    <div class="import-page">
      <textarea v-model="text" class="textarea"></textarea>
      <div class="tools">
        <button @click="importOtp" class="button button-primary">导入</button>
        <button @click="exportOtp" class="button button-primary">导出</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import CryptoJS from 'crypto-js';
import { getStorage, setStorage } from '../utils/storage';

const text = ref('');
const secretKey = '@#$hja82J9l7#0wLK';

const importOtp = () => {
  const data = CryptoJS.AES.decrypt(text.value, secretKey).toString(
    CryptoJS.enc.Utf8,
  );
  console.log(data);
  setStorage('otpList', JSON.parse(data));
};
const exportOtp = () => {
  console.log('导出');
  getStorage('otpList', (result) => {
    // 导出文本文件
    const data = result.map((it: any) => {
      return {
        issuer: it.issuer,
        selector: it.selector,
        submit: it.submit,
        id: it.id,
        otp: it.otp,
      };
    });
    const encryptedData = CryptoJS.AES.encrypt(
      JSON.stringify(data),
      secretKey,
    ).toString();
    const blob = new Blob([encryptedData], { type: 'text/plain' });
    // 3. 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'otp.txt'; // 设置文件名
    // 4. 触发下载
    a.click();
    // 5. 释放内存
    URL.revokeObjectURL(url);
  });
};
</script>
<style scoped lang="scss">
@use '../vars.scss';
.export-page {
  display: flex;
  flex-direction: column;
  gap: 10px;
  .import-page {
    display: flex;
    flex-direction: column;
    gap: 10px;
    .tools {
      display: flex;
      gap: 10px;
    }
    .textarea {
      height: 200px;
      border: 1px solid #ccc;
      border-radius: 5px;
      padding: 10px;
      &:focus {
        outline: none;
        border-color: vars.$primary-color;
      }
    }
  }
}
</style>
